<template>
	<div class="vip">
		<div class="vip_t_txt_all">
			<div class="vip_t_bg">
				<nut-swiper ref="swiperSecRef" @change="onChangeSec">
					<nut-swiper-item style="position: relative" v-for="(item, index) in levelListData" :key="index" :data-le="item.level">
						<ImgT :src="`/imgs/vip/vip_txt_bg.webp`" alt="vip" style="height: 24px" draggable="false" />
					</nut-swiper-item>
				</nut-swiper>
			</div>
			<div class="vip_t_txt flex" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">
				<span @click="handleClick(-2)">VIP{{ curTab === 1 ? 9 : curTab === 2 ? 10 : curTab - 2 }}</span>
				<span @click="handleClick(-1)">VIP{{ curTab === 1 ? 10 : curTab - 1 }}</span>
				<span class="vip_current"
					>VIP{{ curTab }}
					<ImgT src="/imgs/vip/vip_circle.webp" />
				</span>
				<span @click="handleClick(1)">VIP{{ curTab === 9 ? 10 : curTab === 10 ? 1 : curTab + 1 }}</span>
				<span @click="handleClick(2)">VIP{{ curTab === 9 ? 1 : curTab === 10 ? 2 : curTab + 2 }}</span>
			</div>
		</div>
		<div
			class="swiper_btn swiper_btn_l"
			@click="
				() => {
					handlePrev();
					handleSecPrev();
				}
			"
		>
			<div class="icon"></div>
		</div>
		<div
			class="swiper_btn swiper_btn_r"
			@click="
				() => {
					handleNext();
					handleSecNext();
				}
			"
		>
			<div class="icon"></div>
		</div>
		<swiper
			v-if="levelListData.length"
			ref="swiperRef"
			direction="horizontal"
			:autoplay="false"
			:autoHeight="true"
			:speed="500"
			:disableOnIntercation="false"
			:touchStartPreventDefault="false"
			:slides-per-view="'auto'"
			:loop="true"
			class="vip_page_swiper"
			@swiper="onSwiperInit"
			@slideChange="handleSwiperChange"
		>
			<swiper-slide v-for="item in levelListData" :key="item.key">
				<div class="vip-top">
					<div
						class="vip_point"
					>
						<div class="swiper_click_btn">
							<div class="click_rule" @click.stop="levelDataAll.current_vip_level >= item.key + 1 ? goToRule() : null"></div>
							<div class="flex space_between click_bottom">
								<span @click="levelDataAll.current_vip_level >= item.key + 1 ? goToXmRecord() : null"></span>
								<span class="lq_btn" @click="levelDataAll.current_vip_level >= item.key + 1 ? getRebate() : null"> </span>
							</div>
						</div>
					</div>
					<div v-if="levelDataAll.current_vip_level < item.key + 1" class="vip_top_disabled">
						<span>{{ t('level_page_unlock') }}</span>
					</div>
					<div v-if="levelDataAll.current_vip_level > item.key + 1" class="vip_top_disabled">
						<span>{{ t('level_page_unlock_disabled', [levelDataAll.current_vip_level]) }}</span>
					</div>
					<ImgT
						:src="`/imgs/vip/level_${item.key + 1}.webp`"
						alt="vip"
						class="swiper_vip_img"
						draggable="false"
					/>

					<div class="swiper_item_list">
						<div class="swiper_item_top">
							<div class="flex align_center item_top_rule" :style="'background-image: url(/imgs/vip/ruleBg/rule_' + item.key + '.webp)'">
								<span class="icon_wh"></span>
								<span class="rule_txt">{{ t('level_page_rule') }}</span>
							</div>
							<div class="item-top-num" :style="{ opacity: +countNeedBet(item.key) <= 0 ? 0 : 1 }">
								<template v-if="isLocalLoggedIn">
									{{ t('level_page_needBet') }}
									<nut-price :price="countNeedBet(item.key)" size="small" style="color: #fff" :decimal-digits="0" thousands :need-symbol="false" />
								</template>
								<template v-else> -- </template>
							</div>
						</div>
						<!-- 进度条 -->
						<div class="item_pro" :style="'background-image: url(/imgs/vip/proessBg/l_' + item.key + '.webp)'">
							<span v-show="vipProcss(item).rate > 0" class="pro_inner" :style="`width: ${vipProcss(item).rateStr}`"> </span>
						</div>
						<div class="flex space_between align_center swiper_item_bottom">
							<div class="flex space_between align_center bottom_l" :style="'background-image: url(/imgs/vip/awardBg/award_' + item.key + '.webp)'">
								<div class="flex align_center bottom_l-l">
									<span class="icon_jl"></span>
									<span> {{ t('level_page_wash_reward') }}: </span>
									<span v-if="isLocalLoggedIn" class="c-txt">
										<nut-price
											:price="levelDataAll.daily_rebate"
											size="small"
											style="color: #ffd56d"
											:decimal-digits="0"
											thousands
											:need-symbol="false"
										/>
									</span>
									<span v-else class="c-txt">{{ '--' }}</span>
								</div>
								<div class="flex align_center bottom_l_r" :class="[locale == 'vi-VN' ? 'bottom_l_r_vn' : '']">
									<span class="icon_xmjl"></span>
									<span class="jl_txt"> {{ t('level_page_wash_record') }} </span>
								</div>
							</div>
							<div
								class="button bottom_r flex align_center justify_center"
								:style="'background-image: url(/imgs/vip/level_btn_' + item.key + '.webp)'"
							>
								{{ t('level_page_lq') }}
							</div>
						</div>
					</div>
				</div>
				<div class="vip-content">
					<div class="flex space_between align_center vip_c_top">
						<span>VIP{{ item.key + 1}} {{ t('level_page_privilege') }}</span>
						<div class="c_top_r flex align_center" @click="openLevelRule">
							<span>{{ t('level_page_paiTitle') }}</span>
							<span class="icon"></span>
						</div>
					</div>

					<div class="level_list_sec" :class="{ disable_scroll: isDisableLevel }">
						<div v-if="levelDataAll.current_vip_level < item.key + 1" class="vip_top_disabled2">
							<span>{{ t('level_page_unlock') }}</span>
						</div>
						<div v-if="levelDataAll.current_vip_level > item.key + 1" class="vip_top_disabled2">
							<span>{{ t('level_page_unlock_disabled', [levelDataAll.current_vip_level]) }}</span>
						</div>
						<div class="list_item" v-for="(lddItem, index) in levelDyData" :key="index">
							<div v-show="lddItem.levelArr.includes(item.key + 1)" class="flex align_center list_item_l">
								<span class="icon_xx"></span>
								<div class="title_big">{{ t(lddItem.title) }}</div>
								<!--              <div> {{ item.titleSec }} </div>-->
							</div>
							<div class="flex space_between f_wrap list_item_r">
								<div
									v-show="item_1?.levelArr.includes(item.key + 1)"
									class="list_item_r_item"
									v-for="(item_1, index_1) in lddItem.child"
									:key="index + index_1"
								>
									<div :class="`flex space_between list_item_bg ${item_1?.levelArr.includes(item.key + 1) ? '' : 'not'}`">
										<div class="item_l_txt">
											<p class="flex align_center">{{ t(item_1.name) }}</p>
											<div v-show="index < 2" class="flex align_center justify_center vip_rate">
												<!-- 晋级奖励 -->
												<span v-if="item_1.icon === 'level_js'">
													<nut-price
														:price="curVipLevelRewardConfig(lddItem.key).promotional_reward_status?.money"
														size="small"
														style="color: #fff"
														:decimal-digits="0"
														thousands
														:need-symbol="false"
													/>
												</span>
												<!-- 每月礼金 -->
												<span v-else-if="item_1.icon === 'level_lj'">
													<nut-price
														:price="curVipLevelRewardConfig(lddItem.key).gift_money_amount"
														size="small"
														style="color: #fff"
														:decimal-digits="0"
														thousands
														:need-symbol="false"
													/>
												</span>
												<span v-else>
													<template v-if="isLocalLoggedIn">
														{{ toFixedNumber((Number(curVipLevelRewardConfig(lddItem.key).ratio?.split(',')[index_1]) * 1000) / 10) + '%' }}
													</template>
													<template v-else>
														{{ '--' }}
													</template>
												</span>
											</div>
										</div>
										<div :class="`item_img img_${item_1.icon}`">
											<ImgT :key="item_1.icon" :src="`/imgs/vip/${item_1.icon}.webp`" />
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</swiper-slide>
		</swiper>

		<Modal v-model:visible="ruleModal" :title="t('level_page_paiTitle')">
			<div class="popup_body">
				<div class="form_card">
					<div class="form_container vertical">
						<div class="body vertical center">
							<div class="list_tip">{{ t('level_page_paiRule_1') }}</div>
							<div class="list_tip">{{ t('level_page_paiRule_2') }}</div>
							<div class="list_tip">{{ t('level_page_paiRule_3') }}</div>
						</div>
					</div>
				</div>
				<div class="submit_btn flex justify_center">
					<Btn height="44px" width="200px" @click="ruleModal = false" class="submit">{{ t('home_page_confirm') }}</Btn>
				</div>
			</div>
		</Modal>
	</div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { onMounted, ref, watch, defineAsyncComponent, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import PKwebsocket from '@/lolo/Ws';
import { NetPacket } from '@/netBase/NetPacket';
import { showToast } from '@nutui/nutui';
import { storeToRefs } from 'pinia';
import pinia from '@/store';
import { User } from '@/store/user';
import { useRouter } from 'vue-router';
import { toFixedNumber } from '@/utils/publicMethods.ts';
import { Local } from '@/utils/storage';
import { useTouchMove } from '@/hooks/useTouchMove';
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';

const Btn = defineAsyncComponent(() => import('@/components/Btn.vue'));
const Modal = defineAsyncComponent(() => import('@/components/Modal.vue'));

const router = useRouter();
const store = User(pinia);
const { VIPinfo, isLocalLoggedIn }: any = storeToRefs(store);
const { t, locale } = useI18n();
const ruleModal = ref(false);
const swiperSecRef = ref();
const baseVipLevelRewardConfig = [
	// 基本数据
	{
		level: 1,
		target_bet_money: 100,
		promotional_reward_status: {
			status: 0,
			money: '--',
		},
		gift_money_amount: '--',
		ratio: '0.004, 0.006, 0.004, 0.0005, 0.006, 0.004',
	},
	// {
	//   "level": 2,
	//   "target_bet_money": 12500000,
	//   "promotional_reward_status": {
	//     "status": 0,
	//     "money": 28000
	//   },
	//   "gift_money_amount": 38000,
	//   "ratio": "0.004, 0.007, 0.004, 0.0005, 0.007, 0.004"
	// },
	// {
	//   "level": 3,
	//   "target_bet_money": 50000000,
	//   "promotional_reward_status": {
	//     "status": 0,
	//     "money": 100000
	//   },
	//   "gift_money_amount": 150000,
	//   "ratio": "0.0045, 0.0075, 0.0045, 0.0005, 0.008, 0.0045"
	// },
	// {
	//   "level": 4,
	//   "target_bet_money": 150000000,
	//   "promotional_reward_status": {
	//     "status": 0,
	//     "money": 300000
	//   },
	//   "gift_money_amount": 380000,
	//   "ratio": "0.005, 0.008, 0.005, 0.001, 0.0085, 0.005"
	// },
	// {
	//   "level": 5,
	//   "target_bet_money": 500000000,
	//   "promotional_reward_status": {
	//     "status": 0,
	//     "money": 880000
	//   },
	//   "gift_money_amount": 1280000,
	//   "ratio": "0.0055, 0.0085, 0.0055, 0.001, 0.009, 0.0055"
	// },
	// {
	//   "level": 6,
	//   "target_bet_money": 2000000000,
	//   "promotional_reward_status": {
	//     "status": 0,
	//     "money": 3380000
	//   },
	//   "gift_money_amount": 4680000,
	//   "ratio": "0.006, 0.009, 0.006, 0.001, 0.0095, 0.006"
	// },
	// {
	//   "level": 7,
	//   "target_bet_money": 8000000000,
	//   "promotional_reward_status": {
	//     "status": 0,
	//     "money": 13800000
	//   },
	//   "gift_money_amount": 15000000,
	//   "ratio": "0.0065, 0.01, 0.0065, 0.0015, 0.01, 0.0065"
	// },
	// {
	//   "level": 8,
	//   "target_bet_money": 16000000000,
	//   "promotional_reward_status": {
	//     "status": 0,
	//     "money": 26000000
	//   },
	//   "gift_money_amount": 28000000,
	//   "ratio": "0.007, 0.0105, 0.007, 0.0015, 0.0105, 0.007"
	// },
	// {
	//   "level": 9,
	//   "target_bet_money": 32000000000,
	//   "promotional_reward_status": {
	//     "status": 0,
	//     "money": 50000000
	//   },
	//   "gift_money_amount": 53800000,
	//   "ratio": "0.0075, 0.0105, 0.0075, 0.002, 0.011, 0.0075"
	// },
	// {
	//   "level": 10,
	//   "target_bet_money": 150000000000,
	//   "promotional_reward_status": {
	//     "status": 0,
	//     "money": 238000000
	//   },
	//   "gift_money_amount": 258000000,
	//   "ratio": "0.008, 0.012, 0.008, 0.002, 0.012, 0.008"
	// }
];
const levelDataAll: any = ref({
	current_vip_level: 0,
	daily_rebate: 0,
	total_bet_money: 0,
	vip_level_reward_config: [...baseVipLevelRewardConfig],
});
const loading = ref(false);
const curTab = ref(1);
const levelListData = ref([
	{ level: 'VIP0', key: 0 },
	{ level: 'VIP1', key: 1 },
	{ level: 'VIP2', key: 2 },
	{ level: 'VIP3', key: 3 },
	{ level: 'VIP4', key: 4 },
	{ level: 'VIP5', key: 5 },
	{ level: 'VIP6', key: 6 },
	{ level: 'VIP7', key: 7 },
	{ level: 'VIP8', key: 8 },
	{ level: 'VIP9', key: 9 },
]);
const levelDyData = ref([
	{
		key: 'vip',
		title: 'level_page_vip',
		titleSec: 'VIP GIFT MONEY',
		levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
		child: [
			{
				name: 'level_page_bonus',
				icon: 'level_js',
				levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
			},
			{
				name: 'level_page_month_gift',
				icon: 'level_lj',
				levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
			},
		],
	},
	{
		key: 'chip',
		title: 'level_page_code',
		titleSec: 'CHIP DISCOUNT',
		levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
		child: [
			{
				name: 'level_page_live_bet',
				icon: 'level_live',
				levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
			},
			{
				name: 'level_page_slot_bet',
				icon: 'level_game',
				levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
			},
			{
				name: 'level_page_sport_bet',
				icon: 'level_sport',
				levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
			},
			{
				name: 'level_page_lottery',
				icon: 'level_lottery',
				levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
			},
			{
				name: 'level_page_chess',
				icon: 'level_chess',
				levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
			},
			{
				name: 'level_page_eSport',
				icon: 'level_esport',
				levelArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
			},
		],
	},
	{
		key: 'enjoy',
		title: 'level_page_privileges',
		titleSec: 'ENJOY PRIVILEGES',
		levelArr: [4, 5, 6, 7, 8, 9, 10],
		child: [
			{ name: 'level_page_manager', icon: 'level_vip', levelArr: [4, 5, 6, 7, 8, 9, 10] },
			{
				name: 'level_page_access',
				icon: 'level_deposit',
				levelArr: [4, 5, 6, 7, 8, 9, 10],
			},
			{
				name: 'level_page_activity',
				icon: 'level_promo',
				levelArr: [4, 5, 6, 7, 8, 9, 10],
			},
			{ name: 'level_page_domain', icon: 'level_ym', levelArr: [7, 8, 9, 10] },
		],
	},
	{
		key: 'tq',
		title: 'level_page_private',
		titleSec: 'PRIVATE PRIVILEGES',
		levelArr: [8, 9, 10],
		child: [
			{ name: 'level_page_secretary', icon: 'level_sw', levelArr: [8, 9, 10] },
			{ name: 'level_page_reception', icon: 'level_gb', levelArr: [8, 9, 10] },
			// { name: 'level_page_month_gift', icon: 'level_lj', levelArr: [8, 9, 10] },
		],
	},
]);

const isDisableLevel = computed(() => {
	return levelDataAll.value.current_vip_level < curTab.value || levelDataAll.value.current_vip_level > curTab.value;
});

const swiperInstance = ref(null);
const onSwiperInit = (swiper: any) => {
	swiperInstance.value = swiper;
};

const onChangeSec = (index: any) => {
	curTab.value = index + 1;
	// 同步另一个轮播
	swiperInstance.value?.slideTo(index);
};
const handlePrev = () => {
	if (!isLocalLoggedIn.value) {
		store.setLogin(true);
		return;
	}
	let index = curTab.value - 1;
	if (index < 0) {
		index = levelListData.value.length - 1;
	}
	swiperInstance.value?.slideTo(index, 500);
};
const handleNext = () => {
	if (!isLocalLoggedIn.value) {
		store.setLogin(true);
		return;
	}
	let index = curTab.value + 1;
	if (index > levelListData.value.length - 1) {
		index = 0;
	}
	swiperInstance.value?.slideTo(index, 500);
};
const handleSecPrev = () => {
	if (!isLocalLoggedIn.value) {
		store.setLogin(true);
		return;
	}
	swiperSecRef.value?.prev();
};
const handleSecNext = () => {
	if (!isLocalLoggedIn.value) {
		store.setLogin(true);
		return;
	}
	swiperSecRef.value?.next();
};
const handleClick = (step: any) => {
	if (!isLocalLoggedIn.value) {
		store.setLogin(true);
		return;
	}
	let toIndex = curTab.value + step - 1;

	// 处理循环边界情况
	if (toIndex < 0) {
		toIndex = 9; // 最后一个索引
	} else if (toIndex > 9) {
		toIndex = 0; // 第一个索引
	}

	// 同步更新两个轮播
	swiperInstance.value?.slideTo(toIndex, 500);
	swiperSecRef.value?.to(toIndex);
	curTab.value = toIndex + 1;
};
// 跳转到会员等级规则
const goToRule = () => {
	if (!isLocalLoggedIn.value) {
		store.setLogin(true);
		return;
	}
	router.push({ path: '/vip/rule' });
};
// 获取等级数据
const queryData = () => {
	const query = NetPacket.req_vip_info();
	PKwebsocket.instance.send(query, true);
};

// 数据处理
const resultHandle = () => {
	setTimeout(() => {
		loading.value = false;
	}, 300);

	if (Object.keys(VIPinfo.value).length > 0) {
		levelDataAll.value = VIPinfo.value;
		// 设置当前等级
		curTab.value = levelDataAll.value.current_vip_level;
		// 跳转到对应轮播位置
		setTimeout(() => {
			swiperInstance.value?.slideTo(Number(VIPinfo.value.current_vip_level) - 1, 500);
			swiperSecRef.value?.to(Number(VIPinfo.value.current_vip_level) - 1);
		}, 100);
	}
};
// money: 0, result: 2 // 1 成功，2 失败
// const resultHandleClaim = (res: any) => {
//   setTimeout(() => {
//     loading.value = false
//   }, 300)
//   if (res.result === 1) {
//     showToast.success(`${t('level_page_getScu')} ${res.money}`)
//     levelDataAll.value.daily_rebate = 0; //领取成功重置奖励
//   } else {
//     showToast.fail(t('level_page_getFail'))
//   }
// }
// 打开等级规则弹窗
const openLevelRule = () => {
	ruleModal.value = true;
};

// 计算所需投注
const countNeedBet = (key: any) => {
	if (levelDataAll.value.vip_level_reward_config && levelDataAll.value.vip_level_reward_config.length) {
		// const targetArr = levelDataAll.value.vip_level_reward_config[Number(levelDataAll.value.current_vip_level)]
		const targetArr = levelDataAll.value.vip_level_reward_config.find((item: any) => item.level === Number(key) + 1);
		const targetMon = targetArr?.target_bet_money - Number(levelDataAll.value.total_bet_money);
		return targetMon || 0;
	} else {
		return '-';
	}
};
// 计算vip 等级进度
const vipProcss = (data: any) => {
	if (levelDataAll.value.vip_level_reward_config && levelDataAll.value.vip_level_reward_config.length) {
		// levelDataAll.value.total_bet_money = 2654000;
		// const curIndex = levelDataAll.value.current_vip_level == 10 ? 0 : Number(levelDataAll.value.current_vip_level) + 1;
		const curIndex = data.key;
		const targetArr = levelDataAll.value.vip_level_reward_config[curIndex];
		const targetMon = targetArr?.target_bet_money;
		const rate = Number(targetMon) === 0 ? 100 : (Number(levelDataAll.value.total_bet_money) / targetMon) * 100; // 如果 targetMon 为 0 则进度是 100
		const obj = {
			rate: rate,
			rateStr: `${rate}%`,
		};
		// console.log('-----', rate, levelDataAll.value.total_bet_money)
		return obj;
	} else {
		return {
			rate: 0,
			rateStr: `0%`,
		};
	}
};
// 领取返水奖励 ， 是哪个接口
const getRebate = () => {
	console.log('领取---');
	if (!isLocalLoggedIn.value) {
		store.setLogin(true);
		return;
	}
	if (levelDataAll.value.daily_rebate === 0) {
		return showToast.fail(t('level_page_notAward'));
	}
	loading.value = true;
	const query = NetPacket.req_vip_daily_claim();
	PKwebsocket.instance.send(query, true);
};
// 洗码记录
const goToXmRecord = () => {
	if (!isLocalLoggedIn.value) {
		store.setLogin(true);
		return;
	}
	router.push(`/record?page=wash`);
};

const curVipLevelRewardConfig = (index: any) => {
	return levelDataAll.value.vip_level_reward_config[index] || {};
}

watch(
	() => VIPinfo.value,
	(n) => {
		if (n && Object.keys(n).length > 0) {
			levelDataAll.value = n;
			// 设置当前等级
			curTab.value = n.current_vip_level;
			// 跳转到对应轮播位置
			setTimeout(() => {
				swiperInstance.value?.slideTo(Number(n.current_vip_level) - 1, 500);
				swiperSecRef.value?.to(Number(n.current_vip_level) - 1);
			}, 100);
		}
	},
	{ immediate: true }
);

onMounted(() => {
	if (Local.get('user') && Local.get('user').token) {
		queryData();
	}

	// 修改这里，在数据加载完成后跳转到当前等级
	resultHandle();
	if (VIPinfo.value && Object.keys(VIPinfo.value).length > 0) {
		// 设置当前等级
		curTab.value = VIPinfo.value.current_vip_level;
		// 跳转到对应轮播位置
		setTimeout(() => {
			swiperInstance.value?.slideTo(VIPinfo.value.current_vip_level - 1, 500);
			swiperSecRef.value?.to(VIPinfo.value.current_vip_level - 1);
		}, 100);
	}
});

const onSwipeRight = () => {
	handlePrev();
	handleSecPrev();
};

const onSwipeLeft = () => {
	handleNext();
	handleSecNext();
};

// @ts-ignore
const { onTouchEnd, onTouchMove, onTouchStart } = useTouchMove(100, {
	onSwipeLeft,
	onSwipeRight,
});

const handleSwiperChange = (swiper: any) => {
	curTab.value = swiper.realIndex + 1;
	// console.log('swiper.activeIndex', swiper.activeIndex, swiper)
};
</script>

<style lang="scss" scoped>
@use './indexVip.scss';
</style>
